import sys
import cmd
import readline

from completer import TossCompleter
from pytoss._tasks import TaskManager

class TossShell(cmd.Cmd):    
    def __init__(self, *args, **kwargs):
        cmd.Cmd.__init__(self, args, kwargs)
        self.prompt = "toss "
        self.use_rawinput = True
        self.stdin = sys.stdin
        
        self.tasks = TaskManager.get_instance().get_all_tasks()
        
        completions = []
        for task in self.tasks:
            completions.append(task.name)
        
        #set up simple completer
        self.complete = TossCompleter(completions).complete
        readline.set_completer(self.complete)
        readline.parse_and_bind("tab: complete")
        
    def precmd(self, line):
        #check to see if its a toss task first
        try:
            for task in self.tasks:
                if line.split()[0] == task.name:
                    return "toss %s" % line
        except IndexError:
            pass
        return line
    
    def do_toss(self, line):
        """Runs a toss task or shows all avaliable tasks"""
        if not line.strip():
            #need to show all available tasks
            return 0
        for task in self.tasks:
            if line.split()[0] == task.name:
                task.execute()
                return 0
        print "No task %s" % line.split()[0]
        return -1
        
    def do_exit(self, *args):
        sys.exit(0)